package com.ruangong.GitClient.GitHubAPI;

import com.google.gson.Gson;
import android.content.Context;
import android.content.Intent;
import com.google.gson.reflect.TypeToken;
import org.jetbrains.annotations.NotNull;
import com.ruangong.GitClient.app.GitHubFile.FileContentActivity;
import java.io.*;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;


/**
 * Javabeans类，表示GitHub存储库中的文件。
 */
public class GitHubFile {
//    {
//    "name":".gitignore",
//    "path":".gitignore",
//    "sha":"a81c8ee121952cf06bfaf9ff9988edd8cded763c",
//    "size":2035,
//    "url":"https://api.github.com/repos/SilverXQI/Silver_Python/contents/.gitignore?ref=master",
//    "html_url":"https://github.com/SilverXQI/Silver_Python/blob/master/.gitignore",
//    "git_url":"https://api.github.com/repos/SilverXQI/Silver_Python/git/blobs/a81c8ee121952cf06bfaf9ff9988edd8cded763c",
//    "download_url":"https://raw.githubusercontent.com/SilverXQI/Silver_Python/master/.gitignore?token=BA4WQVAYBWTAZYILA4ZV4BDF6LJTK",
//    "type":"file",
//    "_links":
//        {
//        "self":"https://api.github.com/repos/SilverXQI/Silver_Python/contents/.gitignore?ref=master",
//        "git":"https://api.github.com/repos/SilverXQI/Silver_Python/git/blobs/a81c8ee121952cf06bfaf9ff9988edd8cded763c",
//        "html":"https://github.com/SilverXQI/Silver_Python/blob/master/.gitignore"
//        }
//    }

    private String name;
    private String path;
    private String sha;
    private int size;
    private String url; // 注意保持与JSON中的字段名称一致
    private String html_url;
    private String git_url;
    private String download_url;
    private String type;
//    private Links _links;

    public static GitHubFile fromJson(String json) {
        return new Gson().fromJson(json, GitHubFile.class);
    }

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getSha() {
        return sha;
    }

    public void setSha(String sha) {
        this.sha = sha;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }


    // Getter和Setter
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getHtml_url() {
        return html_url;
    }

    public void setHtml_url(String html_url) {
        this.html_url = html_url;
    }

    public String getGit_url() {
        return git_url;
    }

    public void setGit_url(String git_url) {
        this.git_url = git_url;
    }

    public String getDownload_url() {
        return download_url;
    }

    public void setDownload_url(String download_url) {
        this.download_url = download_url;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    /**
     * 获取文件的内容(元素)。
     *
     * @return 包含文件元素的字符串。
     */
    public String getFileInfo() {
        return "Name: " + name + ", Path: " + path + ", SHA: " + sha + ", Size: " + size + ", URL: " + url + ", HTML URL: " + html_url + ", Git URL: " + git_url + ", Download URL: " + download_url + ", Type: " + type;
    }

    /**
     * 显示文件信息。
     */

    public void showFileInfo() {
        System.out.println(getFileInfo());
    }

    /**
     * 获取文件的内容(源码)。
     *
     * @return 包含文件内容的字符串。
     * @throws IOException 如果无法打开连接或存在其他I/O错误，则抛出此异常。
     */
    public String getFileContent() throws IOException {
        URL u = new URL(this.url);
        HttpURLConnection conn = MoMingUtil.createConnection(u);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/vnd.github.v3.raw");//获取内容必须设置为v3.raw
        conn.setRequestProperty("Authorization", "token " + GitHubUser.token);
        StringBuilder content = new StringBuilder();


        try (InputStream inputStream = conn.getInputStream();
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (Exception e) {
            throw new IOException(e);
        } finally {
            conn.disconnect();
        }
        return content.toString();
    }

    /**
     * 显示文件。
     *
     * @throws Exception 如果无法打开连接或存在其他I/O错误，则抛出此异常。
     */
    public void showFileContent() throws Exception {
        System.out.println("File: " + getName() + " " + getUrl());
        System.out.println(getFileContent());
    }

    public void showFileContents(Context context) {
        // 调用getFileContent()方法获取文件内容
        try {
            String fileContent = getFileContent(); // 假设这个方法从URL获取文件内容
            // 这里可以根据需要将文件内容显示在TextView、对话框等控件中
            // 例如，可以启动一个新的Activity来显示文件内容
            Intent intent = new Intent(context, FileContentActivity.class);
            intent.putExtra("fileContent", fileContent);
            context.startActivity(intent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 显示文件夹内文件的属性(递归调用,仅供调试)。
     *
     * @return 文件夹内的所有文件构成的列表
     * @throws IOException 如果无法打开连接或存在其他I/O错误，则抛出此异常。
     */

    public List<GitHubFile> showDirContent() throws IOException {
        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        System.out.println("Dir: " + getName() + " " + getUrl());
        URL url = new URL(this.url);
        HttpURLConnection conn = MoMingUtil.createConnection(url);
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
//        // 使用Gson来解析JSON数据
        Gson gson = new Gson();
        Type listType = new TypeToken<List<GitHubFile>>() {
        }.getType();
        String jsonInput = MoMingUtil.getHttpURLConnectionContent(conn);
        List<GitHubFile> files2 = gson.fromJson(jsonInput, listType);
        for (GitHubFile file : files2) {
            if (file.getType().equals("file")) {
                System.out.println("File: " + file.getName() + " " + file.getUrl());
            } else if (file.getType().equals("dir")) {
//                System.out.println("Dir: " + file.getName() + " " + file.getUrl());
                file.showDirContent();
            }
        }
        System.out.println("---------------------------------------------------------------------------------------");
        conn.disconnect();
        return files2;
    }



    /**
     * 显示文件夹内所有文件内容(文件夹将继续递归调用,文件内容直接打印)。
     *
     * @throws Exception 如果无法打开连接或存在其他I/O错误，则抛出此异常。
     */
    public void showDir() throws Exception {
        System.out.println("Dir: " + getName() + " " + getUrl());
        URL url = new URL(this.url);
        HttpURLConnection conn = MoMingUtil.createConnection(url);
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
//        // 使用Gson来解析JSON数据
        Gson gson = new Gson();
        Type listType = new TypeToken<List<GitHubFile>>() {
        }.getType();
        String jsonInput = MoMingUtil.getHttpURLConnectionContent(conn);
        List<GitHubFile> files2 = gson.fromJson(jsonInput, listType);
        for (GitHubFile file : files2) {
            if (file.getType().equals("file")) {
                file.showFileContent();
            } else if (file.getType().equals("dir")) {
                file.showDir();
            }
        }
//        System.out.println("---------------------------------------------------------------------------------------");
        conn.disconnect();
    }

    /**
     * 返回文件的字符串表示形式。
     *
     * @return 包含文件信息的字符串。
     */
    @NotNull
    public String toString() {
        return "GitHubFile{" +
                "name='" + name + '\'' +
                ", \npath='" + path + '\'' +
                ", \nsha='" + sha + '\'' +
                ", \nsize='" + size + '\'' +
                ", \nurl='" + url + '\'' +
                ", \nhtml_url='" + html_url + '\'' +
                ", \ngit_url='" + git_url + '\'' +
                ", \ndownload_url='" + download_url + '\'' +
                ", \ntype='" + type + '\'' +
                '}';

    }

}
